package com.example.tomato.util;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.example.tomato.model.Model;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

public class DatabaseHandler extends SQLiteOpenHelper {

    private static final int VERSION = 1;
    private static final String NAME = "pomodoroDatabase";
    private static final String ID = "eid";

    private SQLiteDatabase db;

    public DatabaseHandler(Context context) {
        super(context, NAME, null, VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // 创建数据库表格
        Log.i("Database", "-------------------------------Creating Tables--------------------------------");
        db.execSQL("CREATE TABLE IF NOT EXISTS events( eid INTEGER PRIMARY KEY AUTOINCREMENT, eventName TEXT, timeMinutes INTEGER ,timeSecond INTEGER, unlockpw TEXT) ");
        db.execSQL("CREATE TABLE IF NOT EXISTS stats(id INTEGER PRIMARY KEY AUTOINCREMENT, eventName TEXT, timeMinutes INTEGER ,timeSecond INTEGER, date TEXT ) ");
        db.execSQL("CREATE TABLE IF NOT EXISTS user(uid INTEGER PRIMARY KEY, email TEXT, name TEXT, password TEXT) ");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // 更新数据库表格
        Log.i("Database", "-------------------------------Dropping Tables--------------------------------");
        db.execSQL("DROP TABLE IF EXISTS events");
        db.execSQL("DROP TABLE IF EXISTS stats");
        db.execSQL("DROP TABLE IF EXISTS user");
        onCreate(db);
    }

    // 打开数据库连接
    public void openDatabase() {
        db = this.getWritableDatabase();
        onCreate(db);
    }

    // 插入事件
    public void insertEvent(Model evt) {
        ContentValues cv = new ContentValues();
        cv.put("eventName", evt.getTask());
        cv.put("timeMinutes", evt.getTimeMinute());
        cv.put("timeSecond", evt.getTimeSec());
        long res = db.insertOrThrow("events", null, cv);
        if (res == -1) {
            Log.i("Database", "插入失败");
        } else {
            Log.i("Database", "插入成功");
        }
    }

    // 插入统计信息
    public void insertStats(Model evt) {
        ContentValues cv = new ContentValues();
        cv.put("eventName", evt.getTask());
        cv.put("timeMinutes", evt.getTimeMinute());
        cv.put("timeSecond", evt.getTimeSec());
        cv.put("date", evt.getDate());
        long res = db.insertOrThrow("stats", null, cv);
        if (res == -1) {
            Log.i("Database", "插入失败");
        } else {
            Log.i("Database", "插入成功");
        }
    }

    // 获取所有事件
    @SuppressLint("Range")
    public List<Model> getAllEvents() {
        List<Model> eventList = new ArrayList<>();
        Cursor cur = null;
        db.beginTransaction();
        try {
            cur = db.query("events", null, null, null, null, null, null, null);
            if (cur != null) {
                if (cur.moveToFirst()) {
                    do {
                        Model event = new Model();
                        event.setId(cur.getInt(cur.getColumnIndex("eid")));
                        event.setTask(cur.getString(cur.getColumnIndex("eventName")));
                        event.setTimeMinute(cur.getInt(cur.getColumnIndex("timeMinutes")));
                        event.setTimeSec(cur.getInt(cur.getColumnIndex("timeSecond")));
                        eventList.add(event);
                    } while (cur.moveToNext());
                }
            }
        } finally {
            db.endTransaction();
            if (cur != null) {
                cur.close();
            }
        }
        return eventList;
    }

    // 获取统计信息
    @SuppressLint("Range")
    public int getStats(boolean potions, boolean today, String date) {
        int sum = 0;
        int min = 0;
        int sec = 0;

        Cursor cur = null;
        db.beginTransaction();
        try {
            if (today) {
                cur = db.rawQuery("SELECT * FROM stats WHERE date=?", new String[]{date});
            } else {
                cur = db.query("stats", null, null, null, null, null, null, null);
            }

            if (cur != null) {
                if (cur.moveToFirst()) {
                    do {
                        sum++;
                        min += cur.getInt(cur.getColumnIndex("timeMinutes"));
                        sec += cur.getInt(cur.getColumnIndex("timeSecond"));
                    } while (cur.moveToNext());
                }
            }
        } finally {
            db.endTransaction();
            if (cur != null) {
                cur.close();
            }
        }
        min += (int) (sec / 60);
        if (potions) {
            return sum;
        } else {
            return min;
        }
    }

    // 更新事件
    public void updateEvent(int id, String name, int min, int sec) {
        ContentValues cv = new ContentValues();
        cv.put("eventName", name);
        cv.put("timeMinutes", min);
        cv.put("timeSecond", sec);
        String where = "eid =" + id;

        if (db.update("events", cv, "eid=?", new String[]{String.valueOf(id)}) == 0) {
            Log.i("DB TESTINGGGGG", "returned 0 narrrrr cant find nothing");
        }
    }

    // 删除任务
    public void deleteTask(int id) {
        db.delete("events", "eid=?", new String[]{String.valueOf(id)});
    }
}
